use actix_web::{Result, post, web, Responder};

use crate::entity::user_info::check_login;
use crate::entity::user_info::save;
use crate::entity::user_info::UserInfo;

use serde::{Deserialize, Serialize};
use actix_web::web::Json;

# [derive(Deserialize)]
pub struct UserInfoReq {
    user_name: String,
    password: String,
}

// 状态枚举
#[derive(Serialize)]
pub enum Status {
    SUCCESS,
    FAIL,
}

#[derive(Serialize)]
pub struct ResponseEntity {
    status: Status,
    code: i64,
    message: String,
    data: Option<String>,
}

#[allow(dead_code)]
#[post("save")]
pub async fn save_user_info(json: web::Json<UserInfoReq>) -> impl Responder {
    let last_id = save(UserInfo { id: 0, user_name: json.user_name.to_string(), password: Some(json.password.to_string()) });
    return format!("保存的用户ID：{}。", last_id);
}

#[allow(dead_code)]
#[post("login")]
pub async fn login(json: web::Json<UserInfoReq>) -> Result<Json<ResponseEntity>> {
    println!("user_name:{},password:{}", json.user_name.to_string(), json.password.to_string());
    let cnt = check_login(json.user_name.to_string(), json.password.to_string());
    match cnt {
        1 => Ok(Json(ResponseEntity {
            status: Status::SUCCESS,
            code: 200,
            message: "".to_string(),
            data: Some("登陆成功".to_string()),
        })),
        0 => Ok(Json(ResponseEntity {
            status: Status::FAIL,
            code: 200,
            message: "登陆失败，请检查用户名或密码".to_string(),
            data: None,
        })),
        _ => Ok(Json(ResponseEntity {
            status: Status::FAIL,
            code: 200,
            message: "其它错误".to_string(),
            data: None,
        }))
    }
}